package com.iraeta.api;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.iraeta.HikConfig;
import com.iraeta.entity.main.HikDeleteLog;
import com.iraeta.entity.main.WeiXinLiZhi;
import com.iraeta.service.hik.IHikDeleteLogService;
import com.iraeta.service.hik.IWeiXinLiZhiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service(value = "hikApi")
public class HikApi {
    private static final Logger logger = LoggerFactory.getLogger(HikApi.class);

    @Autowired
    private IWeiXinLiZhiService weiXinLiZhiService;
    @Autowired
    private IHikDeleteLogService hikDeleteLogService;
    @Autowired
    private HikConfig hikConfig;

    public final String  ARTEMIS_PATH = "/artemis";

    public void deletePersonByPhoneWarp(String phone){
        logger.info("deletePersonByPhoneWarp[" + phone + "]调用");
        try{
            WeiXinLiZhi weiXinLiZhi = new WeiXinLiZhi();
            weiXinLiZhi.setName("王文静");
            weiXinLiZhi.setMobile(phone);
            this.deletePerson(weiXinLiZhi);
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }

    private void deletePerson(WeiXinLiZhi weiXinLiZhi) throws Exception {
        String phone = weiXinLiZhi.getMobile();
        String personId = this.getUserIdByPhone(phone);
        if(StrUtil.isEmpty(personId)){
            logger.info("手机号[" + phone + "]未找到员工");
            return;
        }
        String url = ARTEMIS_PATH + "/api/resource/v1/person/batch/delete";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", url); //Key 为协议，Value 为接口路径
            }
        };

        JSONObject jsonBody = new JSONObject();
        JSONArray personIds = new JSONArray();
        personIds.add(personId);
        jsonBody.put("personIds", personIds);
        String body = jsonBody.toJSONString();

        Map<String, String> header = new HashMap<>();
        header.put("tagId", "iraeta");
        String result = ArtemisHttpUtil.doPostStringArtemis(new ArtemisConfig(hikConfig.getHost(), hikConfig.getAppkey(), hikConfig.getAppsecret()),
                path, body, null, null,"application/json;charset=UTF-8", header);
        if(StrUtil.isEmpty(result)){
            throw new RuntimeException("调用HIK接口[person/batch/delete]未知错误");
        }
        JSONObject jsonResult = JSONObject.parseObject(result);
        String code = jsonResult.getString("code");
        if(!code.equals("0")){
            throw new RuntimeException("调用HIK接口[person/batch/delete]错误:" + jsonResult.getString("msg"));
        }

        HikDeleteLog hikDeleteLog = new HikDeleteLog();
        hikDeleteLog.setUserid(weiXinLiZhi.getUserid());
        hikDeleteLog.setName(weiXinLiZhi.getName());
        hikDeleteLog.setMobile(weiXinLiZhi.getMobile());
        hikDeleteLog.setHikpersonid(personId);
        hikDeleteLog.setCreateTime(new Date());
        hikDeleteLogService.insertHikDeleteLog(hikDeleteLog);
    }

    private String getUserIdByPhone(String phone) throws Exception {
        String url = ARTEMIS_PATH + "/api/resource/v2/person/personList";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", url); //Key 为协议，Value 为接口路径
            }
        };
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("pageNo", 1);
        jsonBody.put("pageSize", 1000);
        String body = jsonBody.toJSONString();

        String result = ArtemisHttpUtil.doPostStringArtemis(new ArtemisConfig(hikConfig.getHost(), hikConfig.getAppkey(), hikConfig.getAppsecret()),
                path, body, null, null,"application/json;charset=UTF-8");
        if(StrUtil.isEmpty(result)){
            throw new RuntimeException("调用HIK接口[personList]未知错误");
        }
        JSONObject jsonResult = JSONObject.parseObject(result);
        String code = jsonResult.getString("code");
        if(!code.equals("0")){
            throw new RuntimeException("调用HIK接口[personList]错误:" + jsonResult.getString("msg"));
        }
        JSONObject jsonResultData = jsonResult.getJSONObject("data");
        JSONArray personList = jsonResultData.getJSONArray("list");
        for(int i=0; i<personList.size();i++){
            JSONObject p = personList.getJSONObject(i);
            String phoneNo = p.getString("phoneNo");
            if(!StrUtil.isEmpty(phoneNo) && phoneNo.equals(phone)){
                return p.getString("personId");
            }
        }
        return "";
    }

    public void autoProcessLiZhiData(){
        logger.info("autoProcessLiZhiData调用");
        try {
            List<WeiXinLiZhi> topWeiXinLiZhiList = weiXinLiZhiService.selectTopWeiXinLiZhi();
            for (WeiXinLiZhi weiXinLiZhi : topWeiXinLiZhiList) {
                this.deletePerson(weiXinLiZhi);
                Thread.sleep(200L);
            }
        }catch (Exception e){
            logger.error("autoProcessLiZhiData调用异常" + e.getMessage());
        }
    }
}
